<?php
namespace Worker\Controller;

use Workerman\Worker;
use Workerman\Lib\Timer;
use Workerman\Lib\Db;
use Think\Controller;

class IndexController extends Controller {
    
    public function Start(){
        require_once './Workerman/Autoloader.php';
        
        // 初始化一个worker容器，监听1234端口
        $worker = new Worker('websocket://0.0.0.0:2346');
        
        /*
         * 注意这里进程数必须设置为1，否则会报端口占用错误
         * (php 7可以设置进程数大于1，前提是$inner_text_worker->reusePort=true)
         */
        
        $worker->count = 1;
        // worker进程启动后创建一个text Worker以便打开一个内部通讯端口
        $worker->onWorkerStart = function($worker)
        {
            // 开启一个内部端口，方便内部系统推送数据，Text协议格式 文本+换行符
            $inner_text_worker = new Worker('text://0.0.0.0:5678');
            $inner_text_worker->onMessage = function($connection, $buffer)
            {
                global $config;
                // $data数组格式，里面有uid，表示向那个uid的页面推送数据
                $data = json_decode($buffer, true);
                $roomId = isset($data['roomId']) ? $data['roomId'] : 0;
                $state = $data['state'];
                $ret = $this->sendRoomUser($roomId, $buffer);
                
                try{
                    // 建立MySQL链接
                    $db = new Workerman\Lib\Db(C('DB_HOST'), C('DB_PORT'), C('DB_USER'), C('DB_PWD'), C('DB_NAME'), true); 
                      
                    // 房主放弃 
                    if($state == 3){ 
                        $sql = "UPDATE `c_fight_info` SET `state` = 4 WHERE id = '$roomId'";
                        $db->query($sql);
                        
                        //M('fight_info')->where("id = '$roomId'")->save(array('state'=>4));
                    }
                    
                    // 好友放弃
                    if($state == 5){ 
                        $sql = "UPDATE `c_fight_info` SET `state` = 1 WHERE id = '$roomId'";
                        $db->query($sql);
                        
                        //M('fight_info')->where("id = '$roomId'")->save(array('state'=>1));
                    }
                    
                    // 准备开战
                    if($state == 2){
                        
                        // 心跳检测
                        /*$timer_id = Timer::add(1, function() use($roomId,$worker){
                            $data['roomId'] = $roomId;
                            $data['state'] = 10;
                            $data['msg'] = '心跳检测';
                            $data['plus'] = isset($worker->uidConnections[$roomId]) ? count($worker->uidConnections[$roomId]) : '';
                            sendRoomUser($roomId, json_encode($data));
          
                        },'');*/
                        
                        //Timer::add($time, function() use($roomId, $db, $timer_id){
                        
                        // 延迟器执行一次
                        $time = isset($data['plus']) ? intval($data['plus']) : 0;
                        if($time) {
                            Timer::add($time, function() use($roomId, $db){
                                
                                // 设置游戏超时 2游戏中 => 5超时
                                $sql = "UPDATE `c_fight_info` SET `state` = 5 WHERE id = '$roomId' AND `state` = 2";
                                $ret = $db->query($sql);
                                
                                //$ret = M('fight_info')->where("id = '$roomId' AND state = 2")->save(array('state'=>5));
        
                                // 通知客户端
                                if($ret){
                                    $contents['roomId'] = $roomId;
                                    $contents['state'] = 8;
                                    $contents['msg'] = '房间超时';
                                    $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
                                    fwrite($client, json_encode($contents)."\n");    
                                }
        
              
                            },'',false);
                        }           
                    }
        
                }catch(Exception $e){
                    print_r($e);
                }
                
                // 返回推送结果
                $connection->send($ret ? 'ok' : 'fail');
            };
            // ## 执行监听 ##
            $inner_text_worker->listen();
        };
        
        // 针对房间ID推送消息
        $worker->uidConnections = array();
        
        // 消息监听
        $worker->onMessage = function($connection, $data)
        {
            global $worker;
            if(!isset($connection->roomId))
            {
                $connection->roomId = $data;
                $worker->uidConnections[$connection->roomId][] = $connection;
                return;
            }
        };
        
        // 当有客户端连接断开时
        $worker->onClose = function($connection)
        {
            global $worker;
            if(isset($connection->roomId))
            {
                // 连接断开时删除映射
                unset($worker->uidConnections[$connection->roomId]);
            }
        };
        
        // 运行所有的worker
        Worker::runAll();
    }
    
    // 向房间所有用户推送数据
    private function sendRoomUser($roomId, $message)
    {
        global $worker;
        if(isset($worker->uidConnections[$roomId])){
            foreach($worker->uidConnections[$roomId] as $connection)
            {
                $connection->send($message);
            }
            return true;
        }
    }
    
    // 向所有验证的用户推送数据
    private function broadcast($message)
    {
        global $worker;
        foreach($worker->uidConnections as $connection)
        {
            $connection->send($message);
        }
    }
}